/**
 * @description
 * @author aaron
 */
import Editor from 'wangeditor' // npm 安装
import Vue from 'vue';

const {$, BtnMenu} = Editor;
import {SearchSelect} from "@bixiao/ui";
import {cloneDeep} from "lodash"
import {insertImgFn} from "../../../utils/richText";

class UploadImage extends BtnMenu {
    constructor(editor) {
        const $elem = $(`<div class="w-e-menu tl-rich-text-menu">
                <i class="tl-icon-docs-library"/>
            </div>`)
        super($elem, editor)
        // 富文本销毁是销毁
        editor.beforeDestroy(() => this.destroy())
        if (!Array.isArray(editor.txt.eventHooks.clearContentEvents))
            editor.txt.eventHooks.clearContentEvents = []
        editor.txt.eventHooks.clearContentEvents.push(() => this.destroy())
        this.id = `library-${Date.now()}`
    }

    files = []

    /**
     * 点击事件
     */
    clickHandler() {
        const that = this
        // 做任何你想做的事情
        // 可参考【常用 API】文档，来操作编辑器
        const editor = this.editor;
        const libraryApiQuery = editor.config.libraryApiQuery || {};
        const activeKeys = this.files.map(value => value.id)
        SearchSelect.DialogServer({
                title: '文档库上传',
                multiple: true,
                show: true,
                showSubtitle: false,
                searchPlaceholder: "搜索文件名称",
                emptyText: "暂无数据",
                hideAvatar: true,
                labelKey: "file_name",
                valueKey: "id",
                activeKeys: activeKeys,
                querySearchAsync: async (keywords, next, instance) => {
                    instance.loading = true;
                    const result = await Vue.$ajax_pm.Member.memberSearchs({
                        page: 1,
                        page_size: 200,
                        file_name: keywords,
                        ...libraryApiQuery
                    })
                    instance.loading = false;
                    if (result.code === 0) {
                        const list = result.data && Array.isArray(result.data.list) ? result.data.list : [];
                        next(list);
                    } else {
                        Vue.$ele.$message.error(result.message)
                    }
                }
            },
            {
                submit: (list) => that.pushFiles(list)
            }
        )
    }

    pushFiles(list) {
        const that = this;
        const editor = this.editor;
        if (!Array.isArray(list)) return;
        // 是否图片与文本分离
        const customUploadImgSeparate = typeof editor.config.customUploadImgSeparate === "boolean" ?
            editor.config.customUploadImgSeparate : false;
        if (!customUploadImgSeparate) {
            for (let val of list) {
                insertImgFn(editor, {
                    url: val.url,
                    type: val.content_type,
                    name: val.original_name
                })
            }
        } else {
            const customUploadMonitor = editor.config.customUploadMonitor;
            that.files = list;
            const l = that.files.map(value => {
                return {
                    name: value.file_name,
                    size: value.size,
                    type: value.content_type,
                    id: value.id,
                    url: value.url,
                    isOuterFile: true,
                    isLibrary: true,
                    library_id: value.id
                }
            });
            customUploadMonitor && customUploadMonitor['file-change'] && customUploadMonitor['file-change'](cloneDeep(l), that)
        }
    }

    getID() {
        return this.id
    }

    // 菜单是否被激活（如果不需要，这个函数可以空着）
    // 1. 激活是什么？光标放在一段加粗、下划线的文本时，菜单栏里的 B 和 U 被激活，如下图
    // 2. 什么时候执行这个函数？每次编辑器区域的选区变化（如鼠标操作、键盘操作等），都会触发各个菜单的 tryChangeActive 函数，重新计算菜单的激活状态
    tryChangeActive() {
        // 激活菜单
        // 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
        // 2. this.this.isActive === true
        // this.active()
        // // 取消激活菜单
        // // 1. 菜单 DOM 节点会删掉 .w-e-active
        // // 2. this.this.isActive === false
        // this.unActive()
    }

    removeFile(fileID) {
        if (this.files) {
            const fIndex = this.files.findIndex(value => fileID === value.id);
            if (fIndex > -1) {
                this.files.splice(fIndex, 1);
                this.pushFiles(this.files);
            }
        }
    }

    destroy() {
        this.files = []
    }
}

export default UploadImage
